﻿﻿<style>
  @import "../../../static/z39pc/fonts/iconfont.css";
</style>
<template>
  <div id="task-detail" class="task-detail" v-loading="loading" data-task="">
    <div class="task-detail-header">
      <!-- <el-button @click="onEditClick" type="primary" style="float: left;position:relative;top:3px;left:10px;">{{taskEditTxt}}</el-button>任务详情 -->
      <el-tooltip class="item" effect="dark" :content="!isSwitch?'编辑':'关闭'" placement="top-start">
        <el-switch class="switch" v-model="isSwitch" active-color="#13ce66" inactive-color="#ff4949" style="float: left;position:relative;top:10px;left:10px;"
          @change="changeSwitch"></el-switch>
      </el-tooltip>
      <span style="margin-right:30px;">任务详情</span>
      <span class="el-icon-close" @click="closeTaskDetail()"></span>
    </div>
    <div class="task-detail-body" :style="{'height':(taskDetailHeight - (selectedTask.state=='started'||selectedTask.state=='toggle'?230:85) + 'px')}"
      id="taskDetailBody">

      <div class="header-top">
        <div class="title">
          <el-button size="small" type="primary" v-loading="btnLoading" @click="saveTask()" v-show="!(selectedTask.title==taskBigTitle&&selectedTask.desc==taskDesc)">保存</el-button>
          <el-input v-bind:class="{change:!(selectedTask.title==taskBigTitle&&selectedTask.desc==taskDesc)}" placeholder="标题" v-model="taskBigTitle"></el-input>
        </div>
        <div class="desc">
          <el-input type="textarea" :rows="4" v-model="taskDesc" placeholder="描述信息" resize="none">
          </el-input>
        </div>
        <div class="time">
          <ul>
            <li @click="memberDialogVisible=true">
              <span class="iconfont icon-zhaopin1"></span>{{detailObj.leader.nname||'负责人'}}</li>
            <li title="任务开始时间" @click="initPickerDate" style="position:relative"><!--@click="checktime"-->
                <span class="iconfont icon-pingguhuizhang"></span>
                {{showDateOrTime}}
                <el-date-picker  v-model="selectTimeDue" class="timepicker" ref="xxx" popper-class="datepickerchange" align="right" type="datetime" placeholder=""></el-date-picker>
            </li>
            <!-- <li @click="timeNeedDialogVisible=true" title="完成任务需要多少时间"> <span class="iconfont icon-shalou1"></span>{{detailObj.need||'评估'}}</li> -->
            <li title="完成任务需要多少时间" class="popover-wra-li">
              <el-popover ref="popover" placement="bottom" width="350" trigger="hover" popper-class="popper-task-detail">
                <div>
                  <!-- <el-tag style="width:50px;margin:10px 10px 0 0; cursor:pointer" type="success" v-for="item in popoverTimeList"
                  @click.stop="chooseEvlTime(item)">{{item}}</el-tag> -->
                  <el-button style="width:50px;letter-spacing:2px;margin:10px 10px 0 0;padding: 0;height:2rem;" round v-for="item in popoverTimeList"
                    :key="item.id" :type="detailObj.need === item?'primary':'—'" @click.stop="chooseEvlTime(item)">{{item}}</el-button>
                  <div style="margin:30px">
                    手动输入：
                    <el-input style="width:4rem;border:none;" type="text" size="small" v-model="popoverTime.hour"></el-input>
                    <el-input style="width:4rem;border:none;" type="text" size="small" v-model="popoverTime.minute"></el-input>
                    <el-button v-if="popoverTimeSure" @click.stop="confirmEvlTime">确定</el-button>
                  </div>
                </div>
              </el-popover>
              <el-button v-popover:popover style="font-size:0.75rem;color:rgba(0, 0, 0, 0.54);background-color:#fff;border:none;height30px;position:relative;top:-2px;">
                <span class="iconfont icon-shalou1"></span>{{detailObj.need?formatTime(detailObj.need):'评估'}}</el-button>
            </li>
            <li title="要到结束时间的提醒方式">
              <!-- <datetime v-model="dueValue" clear-text="清空" @on-clear="clearDue" format="YYYY-MM-DD HH:mm" :minute-list="['00','05','10', '15','20','25', '30','35','40','45','50','55']"
                @on-change="changeDue" title="开始闹铃"></datetime> -->
              <el-popover ref="popover" placement="bottom" width="350" trigger="hover" popper-class="popper-task-detail">
                <el-card shadow="hover">
                  <el-row>
                    <el-col :span="12">
                      <el-radio-group v-model="remind">
                        <el-radio-button :label="item.value" v-for="item in remindBtnsDef" :key="item.value" v-if="item.type!='info'">
                          {{item.label}}
                        </el-radio-button>
                      </el-radio-group>
                    </el-col>
                    <el-col :span="12">
                      <el-radio-group v-model="remindTypeValue">
                        <el-radio-button :label="item.value" v-for="item in remindTypeBtnsDef" :key="item.value" v-if="item.type!='info'">
                          {{item.label}}
                        </el-radio-button>
                      </el-radio-group>
                    </el-col>
                  </el-row>
                  <div class="popper-task-detail-footer">
                    <el-button style="float: right; padding: 3px 0" type="text" @click="chooseRemind">完成</el-button>
                  </div>
                </el-card>
              </el-popover>
              <span v-popover:popover>
                <span class="icon iconfont icon-shizhong"></span>{{remind?(remind+"m"):"提醒方式"}}</span>
            </li>
          </ul>
        </div>
        <div class="tag-container detail-tags-swiper">
          <ul @click="showSetTagDialog()" class="swiper-wrapper">
            <li class="swiper-slide">
              <span class="iconfont icon-add4"></span>添加</li>
            <li v-for="(item,index) in detailObj.tagsArr" :key="index" v-if="systemTags.indexOf(item.key)<0" class="swiper-slide">
              <!--{{tagsRepeatDic[item.value]}}-->
              {{(item.key=='repeat'&&tagsRepeatDic[item.value])?tagsRepeatDic[item.value]:item.name}}
              <!--重复任务标签-->
            </li>
          </ul>
        </div>
      </div>

      <div class="header-middle">
        <el-button size="small" type="primary" v-loading="btnLoading" @click="addTask()" v-show="taskSmallTitle!=''">创建</el-button>
        <span class="el-icon-circle-cross"></span>
        <el-input placeholder="新建子任务" v-model="taskSmallTitle"></el-input>
      </div>

      <div class="header-bottom" v-show="childrenList.length>1">
        <ul class="children-list">
          <li v-for="(item,index) in childrenList" :key="index" @click="changeTask(item)" :class="taskStatusClass(item.state)">
            <div style="font-weight: bold;" :title="item.title">
              <span :class="item.id==selectedTask.id?'selected':'not-selected'"></span>
              <el-checkbox v-model="item.finished" @change="changeTaskStatusBox(item,item.finished)" style="margin-right: 10px;"></el-checkbox>{{item.title}}
            </div>
          </li>
        </ul>
        <!--<div class="dynamic">
          <div class="title">
            <span>动态</span><span style="float:right">显示操作记录</span>
          </div>
          <div class="dynamic-content">
            <ul>
              <li>
                <img src="../../../static/images/avatar.png" alt="" />
                <div>
                  <p><span class="dynamic-user-name">王小儿</span><span class="dynamic-time">02-10 18:20</span></p>
                  <p>打飞机啊的合法好的法律阿斯顿放假咯是否啊是符合阿斯弗阿三</p>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="send-message">

        </div>-->
      </div>

    </div>
    <div class="header-top time-remind" v-if="selectedTask.state!=''">
      <div class="cal-timer">
        {{clockParams.remainTime}}
      </div>
      <div class="time" style="border-bottom: 0;">
        <ul>
          <li title='预计完成'>{{clockParams.dueDone||'预计完成'}}</li>
          <li title='提醒时间'>{{(clockParams.finishTime&&clockParams.finishTime.split(' ')[1])||'提醒时间'}}</li>
          <li title="提醒方式">
            <span class="icon iconfont icon-kuaijiefangshi"></span>
            <span class="grid-center">{{clockParams.remindType||"提醒方式"}}</span>
          </li>
          <li title='继续添加评估时间' @click="timeAddDialogVisible=true">加时</li>
        </ul>
      </div>
    </div>
    <div class="task-detail-footer">
      <el-button type="primary" size="small" v-if="selectedTask.state!='started'&&selectedTask.state!='toggle'&&selectedTask.state!='done'"
        @click="changeTaskState('started')">开始</el-button>
      <el-button type="primary" size="small" v-if="selectedTask.state=='toggle'" @click="changeTaskState('toggle')">继续</el-button>
      <el-button type="primary" size="small" v-if="selectedTask.state=='started'" @click="changeTaskState('toggle')">暂停</el-button>
      <el-button type="primary" size="small" v-if="selectedTask.state!='done'" @click="changeTaskState('done')">完成</el-button>
      <el-button type="primary" size="small" v-if="selectedTask.state!='done'" @click="changeTaskState('cancelled')">取消</el-button>
      <!--<el-button type="primary" size="small" v-if="selectedTask.state=='done'" @click="changeTaskState('')">重置</el-button>-->
      <el-button v-if="selectedTask.state!='done'" type="primary" size="small">求助</el-button>
      <el-button type="primary" size="small" v-if="selectedTask.state=='done'" @click="doTaskMend(selectedTask)">修改</el-button>
      <el-button v-if="selectedTask.state=='done'" type="primary" size="small">任务总结</el-button>
    </div>

    <!--选择need时间-->
    <el-dialog title="选择时间" :visible.sync="timeNeedDialogVisible" size="tiny">
      <el-time-select style="margin:0 auto;" v-model="selectTimeNeed" :editable="false" :picker-options="{
        start: '00:00',
        step: '00:15',
        end: '24:00'
      }" placeholder="选择评估时间"></el-time-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="timeNeedDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="setTimeNeed()">确 定</el-button>
      </span>
    </el-dialog>
    <!--选择加时时间-->
    <el-dialog title="选择时间" :visible.sync="timeAddDialogVisible" size="tiny">
      <el-time-select style="margin:0 auto;" v-model="selectTimeAdd" :editable="false" :picker-options="{
        start: '00:00',
        step: '00:05',
        end: '24:00'
      }" placeholder="选择加时时间"></el-time-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="timeAddDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="setTimeAdd()">确 定</el-button>
      </span>
    </el-dialog>    
    <!--选择负责人-->
    <el-dialog title="选择负责人" :visible.sync="memberDialogVisible" size="tiny">
      <el-select v-model="selectedMember" filterable='' placeholder="请选择负责人" style="width: 100%;">
        <el-option v-for="item in memberList" :label="item.name" :value="item.fuid" :key="item.fuid">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="memberDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="setTaskMember()">确 定</el-button>
      </span>
    </el-dialog>
    <!--选择标签-->
    <el-dialog title="添加标签" :visible.sync="tagDialogVisible" class="tmp-dialog">
      <h6>常用标签</h6>
      <div>
        <div class="all-tag">
          <span v-for="(item,index) in commonTagsList" :key="index" :class="item.active?'active':''" @click="tagsClick(item,'common')">{{item.name}}</span>
        </div>
      </div>
      <h6 style="margin-top:10px">项目标签</h6>
      <div>
        <div class="all-tag">
          <span v-for="(item,index) in projects" :key="index" :class="item.active?'active':''" @click="tagsClick(item,'project')">{{item.title}}</span>
        </div>
      </div>
      <h6 style="margin-top:10px">重复任务</h6>
      <div>
        <div class="all-tag">
          <span v-for="(item,index) in tagsRepeatList" :key="index" :class="item.active?'active':''" @click="tagsClick(item,'repeat')">{{item.name}}</span>
        </div>
      </div>
      <h6 style="margin-top:10px">所有标签</h6>
      <div>
        <div class="all-tag">
          <span v-for="(item,index) in allTags" :key="index" v-if="systemTags.indexOf(item.key)<0" :class="item.active?'active':''"
            @click="tagsClick(item,'all')">{{item.name}}</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tagDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="setTaskTag()" size="small">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import swiper from 'swiper';
  import api from '../../api';
  import moment from "moment";
  import _ from 'underscore';
  import {
    mapState,
    mapActions
  } from 'vuex'
  import {taskAndTag} from "../../common/mixin";
  import { logic  } from "../../common/mixinTaskLogic";
  import {mixinPc} from "../../common/mixinPc";
  import {relative} from 'path';

var remindBtnsArr = [{
            label: '提前时间<br/><span style="color:#666;font-size:12px;">任务结束前提前几分钟提醒</span>',type: 'info'},
          // {label: '不提醒',value: ''},
          {label: '提前05分钟',value: '5'},
          {label: '提前10分钟',value: '10'},
          {label: '提前15分钟',value: '15'},
          {label: '提前20分钟',value: '20'}, 
          {label: '提前30分钟',value: '30'}];
var  remindTypeBtnsArr=[{
            label: '闹钟提醒方式<br/><span style="color:#666;font-size:12px;">任务结束前和超时共2次提醒</span>',type: 'info'},
          {label: '系统闹钟',value: '1'},
          {label: '公众号提醒',value: '2'},
          {label: 'APP消息',value: '3'},
          {label: '短信提醒',value: '4'},
          {label: '电话呼叫',value: '5'}]

  var initPage = function () {
  }
  var tagSlider = function () {
    var swiper = new Swiper('.detail-tags-swiper', {
      slidesPerView: 'auto',
      spaceBetween: 0,
      freeMode: true,
      freeModeMomentumRatio: 0.5,
      freeModeMomentumBounce: false,
      freeModeMomentum: true,
      scrollbarHide: true
    });
    return swiper
  }
  export default {
    name: 'taskDetail',
    data() {
      return {
        remindBtnsDef: remindBtnsArr ,
        remindTypeBtnsDef: remindTypeBtnsArr,
        blurFocus:true,
        remind: 5,
        remindTime: '',
        remindType: '', //'',
        remindTypeValue: 1,
        lastRemainTime:"", //解决完成任务后,显示评估时间
        taskEditTxt: '编辑',
        isSwitch: false,
        taskId: 0,
        tagSwiper: '',
        taskDetailHeight: '',
        taskDetail: '',
        dueValue: "",
        dueValueDialog: false,
        btnLoading: false,
        loading: false,
        taskBigTitle: '',
        taskDesc: '',
        taskSmallTitle: '',
        parentTask: '',
        childrenList: '',
        showClock: false,
        taskState: "done", //  "", //
        popoverTime: {
          hour: '',
          minute: ''
        },
        clockParams: {
          dueDone: '',
          finishTime: '',
          remainTime: '00:00:00',
          remindType: ''
        },
        clockTimer: '',
        lastTaskIdState:"",
        selectedTask: '', //被选中的任务
        timeNeedDialogVisible: false,
        selectTimeNeed: '', //选中的need时间
        initPickerTime: '',
        selectTimeDue: '', //选中的due时间
        selectTimeAdd: '',
        timeAddDialogVisible: false, //选择加时时间
        memberDialogVisible: false, //成员dialog
        memberList: [],
        selectedMember: '',
        tagDialogVisible: false, //标签dialog
        allTags: [],
        memberListDic: {},
        notShowTagsArr: [], // 任务不显示的标签
        popoverTimeList: ["00:05", "00:10", "00:15", "00:20", "00:25", "00:30", "00:35", "00:40", "00:45", "00:50",
          "00:55", "01:00", "01:05", "01:10", "01:15", "01:20", "01:25", "01:30", "01:35", "01:40", "01:45", "01:50",
          "01:55", "02:00", "02:05", "02:10", "02:15", "02:20", "02:25", "02:30", "02:35", "02:40", "02:45", "02:50",
          "02:55", "03:00"
        ],
        tagsRepeatList: [{
          name: "每天",
          key: "repeat",
          active: false,
          value: 'D'
        }, {
          name: "每周1",
          key: "repeat",
          active: false,
          value: 'W1'
        }, {
          name: "每周2",
          key: "repeat",
          active: false,
          value: 'W2'
        }, {
          name: "每周3",
          key: "repeat",
          active: false,
          value: 'W3'
        }, {
          name: "每周4",
          key: "repeat",
          active: false,
          value: 'W4'
        }, {
          name: "每周5",
          key: "repeat",
          active: false,
          value: 'W5'
        }, {
          name: "每周6",
          key: "repeat",
          active: false,
          value: 'W6'
        }, {
          name: "每周日",
          key: "repeat",
          active: false,
          value: 'W7'
        }, {
          name: "每月",
          key: "repeat",
          active: false,
          value: 'M'
        }, {
          name: "每年",
          key: "repeat",
          active: false,
          value: 'Y'
        }],
        tagsRepeatDic: {},
        commonTagsList: [],
        detailObj: {
          taskId: '',
          leader: '',
          due: '',
          need: '',
          clock: '',
          remind: 5,
          tagsArr: [],
          tagsObj: {}
        },
        systemTags: ["need", "used", "usedCalc", "created", "started", "done", "toggle", "cancelled", "due", "to",
          "remind"
        ],
      }

    },
    mixins: [taskAndTag, mixinPc,logic],
    computed: {
      ...mapState({
        uid: state => state.vux.uid,
        taskAll: state => state.z39.taskAll,
        tagDic: state => state.z39.tagDic,
        taskDic: state => state.z39.taskDic,
        tagitems: state => state.z39.tagitems,
        tagitemDic: state => state.z39.tagitemDic,
        members: state => state.z39.members,
        memberDic: state => state.z39.memberDic,
        projects: state => state.z39.projects,
      }),
      popoverTimeSure() {
        function isNumber(obj) {
          return typeof obj === 'number' && !isNaN(obj)
        }
        if (isNumber(+this.popoverTime.hour) && isNumber(+this.popoverTime.minute) && (this.popoverTime.hour || this.popoverTime
            .minute) && +this.popoverTime.minute < 60) return true
        return false
      },
      //时间显示
      showDateOrTime(){
        if(this.detailObj.due != '') {
          var  datestr = moment(this.detailObj.due).format("MM-DD");
          var  timestr = moment(this.detailObj.due).format("HH:mm");
          // console.log(datestr,timestr)
          if(timestr=='' || timestr == '00:00') return datestr;
          else return  timestr;
        }else {
          return '开始时间';
        }
      }
    },
    watch: {
      "selectedTask": {
        handler() {
          this.detailObj.leader = (this.selectedTask.tags && this.selectedTask.tags.to && this.memberListDic['fuid_' +
            this.selectedTask.tags.to]) || "";
          this.detailObj.due = (this.selectedTask.tags && this.selectedTask.tags.due) || '';
          this.detailObj.need = (this.selectedTask.tags && this.selectedTask.tags.need) || '';
          this.detailObj.remind = (this.selectedTask.remind && this.selectedTask.tags.remind) || '';
          this.remind = (this.selectedTask.remind && this.selectedTask.tags.remind) || '';
          this.detailObj.tagsObj = Object.assign({}, this.selectedTask.tags);
          console.log(this.detailObj)
          this.initPickerTime = this.detailObj.due||"";
          if (this.detailObj.tagsObj.remind) {
            var tempR = this.detailObj.tagsObj.remind;
            var tempA = tempR.split("_");
            this.detailObj.remind = tempR;
            this.remind = tempA[0];
            this.remindTypeValue = tempA[1];
            var tempt = parseInt(tempA[1] || 1); //
            tempt = this.remindTypeBtnsDef[tempt].label;
            this.remindType = tempt.substr(0, tempt.length - 2);
            this.changeRemindSelect();
          } else {
            this.remind = '';
          }
          if (this.selectedTask.pid) {
            this.detailObj.tagsObj.pid = this.selectedTask.pid;
          }
          //  let times= this.getDone2Due(this.taskDic[this.selectedTask.id]);
          // this.clockParams.finishTime=times.dueDone;
          // this.clockParams.remainTime=times.remindTime;
          // this.clockParams.remindType=this.remindType;
          // console.log(this.getDone2Due(this.taskDic[this.selectedTask.id]))
          clearInterval(this.clockTimer);
          this.setClockParams();

          // this.doCountDown();

          // console.log("tagitem:", temp, _.clone(this.detailObj), _.clone(this.detailObj.tags), this.to, this.due, this.need,
          //   this.remind);
        },
        deep: true,
      },
      "selectedTask.id": function () {
        var _this = this;
        this.lastRemainTime = "";
        this.detailObj.tagsArr = [];
        if (!this.selectedTask.id) return;
        api.taskGet({
          id: this.selectedTask.id
        }).then(data => {
          console.log(_this.detailObj.tagsArr)
          _this.detailObj.tagsArr = data.data.tags;
          //          _this.selectedTask.state=data.data.state;
        })
      },
      taskDic: {
        handler() {
          if (this.selectedTask && this.taskDic[this.selectedTask.id]) {
            this.selectedTask.state = this.taskDic[this.selectedTask.id].state
            this.selectedTask.finished = this.taskDic[this.selectedTask.id].finished
            this.selectedTask.tags = this.taskDic[this.selectedTask.id].tags;
            //            this.selectedTask.tagsArr=this.taskDic[this.selectedTask.id].tagsArr;

            api.taskGet({
              id: this.selectedTask.id
            }).then(data => {
              this.detailObj.tagsArr = data.data.tags;
            })

          }
        },
        deep: true,
      },
      'members': function () {
        var _this = this;
        this.memberList = this.members;
        this.memberList.forEach(function (item) {
          _this.memberListDic['fuid_' + item.fuid] = item;
        })
      },
      projects: function () {
        this.projects.forEach(item => {
          this.$set(item, 'active', false)
        })
      },
      selectTimeDue:function(val)
      {
        if (!val || this.initPickerTime == val) return ; //初始化数值
        this.detailObj.due = moment(this.selectTimeDue).format('YYYY-MM-DD HH:mm').replace(" 00:00","");
        console.log(val,this.selectTimeDue)
        this.saveTask()
      }
    },
    filters: {

    },
    methods: {
      initPickerDate(){
        this.selectTimeDue = this.initPickerTime;
      },
      formatTime: function (secend) {
        return formatUsed(secend);
      },
      chooseRemind() {
        console.log("chooseEdit");
        var taskitem = this.selectedTask; //this.taskDic[this.selectedTask.id]
        if (taskitem == undefined) return; //点击取消.
        this.changeRemind(taskitem, this.remind, this.remindTypeValue);
        // this.getDone2Due() ;
      },
      changeRemindSelect() { //修改弹出闹钟显示的文字
        var index = this.remind / 5;
        var temp = index < 4 ? (index == 0 ? "不提醒" : this.remindBtnsDef[index].label) : `提前${this.remind}分钟`;
        console.log(this.remindTypeValue)
        var temp1 = this.remindTypeBtnsDef[this.remindTypeValue].label;
        this.remindValue = [temp, temp1];
      },
      changeRemind(task, remind, remindValue) {
        if (!task) return; //刚今日页面
        var value = `${remind}_${remindValue}`;
        this.remind = remind;
        this.detailObj.remind = value;
        console.log(value)
        if (task["tags"] == undefined || value == task.tags.remind) return;
        // this.saveTask()
        this.doTagSet(task, "remind", value).then((data) => {
          this.checkSetClock(task);
        })
      },
      setDueValue() {
        if (!this.dueValue) return this.showNotice('请选择时间', 'warning');
        this.dueValueDialog = false;
        this.detailObj.clock = moment(this.dueValue).format('MM-DD');
        this.saveTask()
      },
      onEditClick: function () {
        if (this.isSwitch) {
          // $('.task-detail-container').blur()
          // this.taskEditTxt = '关闭';
          var taskId = this.taskId;
          var taskDetail = this.taskDesc;
          $('#task-detail').attr('data-task', JSON.stringify(taskDetail));
          this.$parent.openTaskEditor(taskId, this.taskDesc);
          $('#taskeditor').focus()
        } else {
          this.taskDesc = this.$parent.getEditorContent();
          this.$parent.closeTaskEditor();
          // this.taskEditTxt = '编辑';
        }
      },
      setClockParams: function () {
        var { dueDone } = this.getDone2Due(this.selectedTask);
        let time = dueDone.substr(11);
        this.clockParams.dueDone = time ;// this.detailObj.due || '';
        this.clockParams.remainTime = '00:00:00';
        this.clockParams.finishTime = '';
        if (this.clockParams.dueDone && this.detailObj.tagsObj.need) {
          var temp,h,m,need ;
          need = this.detailObj.tagsObj.need;
          if(_.isString(need) && need.indexOf(":")==-1) need = parseInt(need);
          if( typeof need==='number' && isFinite(need) ){
            h = Math.ceil(need/3600),
            m = Math.ceil(need%3600/60);
          } else{ //旧代码,字符形式的兼容.
            temp = need.split(':');
            h = temp[0] ,m = temp[1] ;
          }
          var finishMom = moment(this.detailObj.due).add(h, 'h').add(m, 'm')
          this.clockParams.finishTime = finishMom.format('YYYY-MM-DD HH:mm');
          var usedTime = this.detailObj.tagsObj.used;
          var remainTime = need;
          if (usedTime) remainTime = need - getSecond(usedTime) ;
          
          if (_.isString(remainTime) && remainTime.split(':').length == 2) {
            remainTime += ':00';
          } //旧代码可删除
          if(this.lastRemainTime)  this.clockParams.remainTime =this.lastRemainTime ;
          else this.showClockTime(remainTime);
          // this.clockParams.remainTime = formatTimeHM(remainTime,true);
          if(this.selectedTask.state=="started") this.timerInterval(remainTime,this.selectedTask);
        }
        this.clockParams.remindType = this.remindType;
      },
      timerInterval: function (time,task) {
        var started,st,now,used,tags = task.tags ;
        used = 0 ;
        now = moment().valueOf();
        st = tags.started;
        if(st) used =(now - moment(st).valueOf())/1000;
        used = Math.ceil(used);
        // used = tags.used || 0 ;
        // started = tags.toggle || tags.started || moment();

        // var tids = task.id+task.state + this.remindValue;
        // if(this.lastTaskIdState == tids) return ;
        // this.lastTaskIdState = tids ;
        var rTime = time;
        var eTime = '00:00:00';
        clearInterval(this.clockTimer)
        if (rTime >0) { // rTime != '00:00:00'
          var temp1,h1,m1,s1,allSeconds;
          if(_.isNumber(rTime)){ //旧数据格式，需要删除.
            allSeconds = rTime ;
          }else{
              temp1 = rTime.split(':');
              h1 = Number(temp1[0]),
              m1 = Number(temp1[1]),
              s1 = Number(s1 = temp1[2])
              allSeconds = h1 * 3600 + m1 * 60 + s1;
          }
          allSeconds -= used ; //减去消耗时间
          this.showClockTime(allSeconds);
          if(task.state =="done" ||task.state =="cancelled") return ;
          this.clockTimer = setInterval(()=> {
            allSeconds--;
            this.showClockTime(allSeconds);
          }, 1000)
        }
      },
      showClockTime(time){
        var num = Math.abs(time);
        var h2 = parseInt(num / 3600);
        var m2 = parseInt((num - h2 * 3600) / 60);
        var s2 = num - h2 * 3600 - m2 * 60;
        h2 = (String(h2).length < 2 ? ('0' + h2) : h2);
        m2 = (String(m2).length < 2 ? ('0' + m2) : m2);
        s2 = (String(s2).length < 2 ? ('0' + s2) : s2);
        this.lastRemainTime=  (time<0?"-":"")+ h2 + ':' + m2 + ':' + s2;
        this.clockParams.remainTime =this.lastRemainTime;
      },
      changeTaskState: function (state) {
        var realState = state;
        this.selectedTask.state = state;
        if (this.selectedTask.state == 'toggle' && state == 'toggle') {
          realState = 'started';
          this.selectedTask.state = "started";
        }
        if (realState == 'started') {
          if (this.clockTimer) {
            clearInterval(this.clockTimer)
          }
          console.log("remainTime:",this.clockParams.remainTime)
          this.timerInterval(this.clockParams.remainTime,this.selectedTask);
        } else {
          clearInterval(this.clockTimer)
        }
        // var taskItem = this.taskDic[this.selectedTask.id];
        var startedVal = moment().format("YYYY-MM-DD HH:mm");
        this.doTaskEdit(this.selectedTask, state, startedVal).then((data) => {
          this.checkSetClock(this.selectedTask, startedVal);
        });
      },
      showTaskDetail: function (taskId) {
        this.showClock = false;
        this.loading = true;
        this.resetForm();
        var _this = this;
        this.taskDetail = this.taskDic[taskId]
        console.log(this.taskDetail)
        api.taskGet({
          id: taskId
        }).then(data => {
          this.loading = false;
          if (data.errno != 0) {
            _this.showNotice(data.errmsg, 'warning');
            return Promise.reject(data.errmsg);
          }
          data = data.data;
          //添加到stroe
          let childtasks = data.tasks || [];
          let allTasks = [data].concat(childtasks);
          allTasks.forEach(function (item) {
            item.tagsArr = item.tags;
          })
          _this.$store.commit({
            type: "z39/taskToDB",
            tasks: allTasks,
            act: "add"
          });
          _this.$store.commit({
            type: "z39/taskCurr",
            task: data
          });
          //end
          _this.parentTask = data
          _this.taskBigTitle = data.title;
          _this.taskDesc = data.desc;

          allTasks.forEach(function (item, index) {
            if (index == 0) {
              _this.selectedTask = item;
            }
            if (item.state == 'done') {
              item.finished = true;
            } else {
              item.finished = false;
            }
          })
          _this.childrenList = allTasks
          this.tagSwiper.setWrapperTranslate(0)
          setTimeout(() => {
            this.tagSwiper.updateSlidesSize()
          }, 500)
        })
      },
      resetForm: function () {
        this.taskBigTitle = '';
        this.taskDesc = '';
        this.childrenList = '';
        this.selectedTask = ''
        this.detailObj = {
          taskId: '',
          leader: '',
          due: '',
          need: '',
          remind: '',
          tagsArr: [],
          tagsObj: {}
        }
        this.allTags = this.tagitems.map(function (item, index, arr) {
          var item1 = Object.assign({}, item)
          item1['active'] = false
          return item1;
        })
      },
      changeTask: function (item) {
        clearInterval(this.clockTimer)
        this.taskBigTitle = item.title;
        this.taskDesc = item.desc;
        this.selectedTask = item;
      },
      addTask: function () {
        var _this = this;
        if (!this.taskSmallTitle) {
          this.$message({
            message: '请输入任务标题',
            type: 'warning'
          });
          return;
        }
        this.btnLoading = true;
        api.taskAdd({
          parid: this.parentTask.id,
          title: this.taskSmallTitle,
          desc: ''
        }).then(data => {
          _this.btnLoading = false;
          if (data.errno != 0) {
            _this.showNotice(data.errmsg, 'warning');
            return Promise.reject(data.errmsg);
          }
          _this.taskSmallTitle = '';
          data = data.data;
          data.finished = false;
          _this.childrenList.push(data);
          _this.$store.commit({
            type: "z39/taskToDB",
            tasks: [data],
            act: "add"
          });
        })
      },
      delTask: function () {
        var _this = this;
        var isParent = false;
        if (this.selectedTask.id == this.parentTask.id) {
          isParent = true;
        }
        _this.btnLoading = true;
        api.taskDel({
          id: this.selectedTask.id
        }).then(data => {
          _this.btnLoading = false;
          if (data.errno != 0) {
            _this.showNotice(data.errmsg, 'warning');
            return Promise.reject(data.errmsg);
          }
          if (isParent) {
            _this.$store.commit({
              type: "z39/taskToDB",
              tasks: [{
                id: id
              }],
              act: "del"
            });
          } else {
            _this.childrenList = _this.childrenList.filter(function (item) {
              return item.id != _this.selectedTask.id;
            })
            _this.childrenList[0].checked = true;
          }

        })
      },
      saveTask: function () {
        var _this = this;
        this.btnLoading = true;
        //设置任务
        var taskParams = {
          title: this.taskBigTitle,
          desc: this.taskDesc,
          id: this.selectedTask.id,
        };
        if (this.selectedTask.pid && !this.detailObj.tagsObj['pid']) {
          //如果原先有项目id现在没有
          taskParams.pid = null;
        } else {
          taskParams.pid = this.detailObj.tagsObj['pid']
        }
        this.taskSet(taskParams, this.selectedTask)
        //先循环自带的tag,如果没有就删除
        this.selectedTask.tagsArr && this.selectedTask.tagsArr.forEach(function (item) {
          //key为due need to时需要判断
          if (item.key == 'due' || item.key == 'need' || item.key == 'to' || item.key == 'remind') {
            return false;
          } else if (_this.detailObj.tagsObj[item.key] == undefined) {
            if (_this.tagDic[_this.selectedTask.id + '_' + item.key]) {
              _this.tagDel(_this.tagDic[_this.selectedTask.id + '_' + item.key], true, _this.selectedTask);
            }

          }

        })
        //再循环新增的tag,如果没有就添加
        this.detailObj.tagsArr.forEach(function (item) {
          //key为due need to时需要判断
          if (item.key == 'due' || item.key == 'need' || item.key == 'to' || item.key == 'remind') {
            return;
          } else if (_this.selectedTask.tags[item.key] == undefined) {
            //如果没有就新增
            _this.tagAdd({
              taskid: _this.selectedTask.id,
              key: item.key,
              value: item.value
            }, true, _this.selectedTask)
          } else if (item.value != _this.selectedTask.tags[item.key]) {
            //如果有但不一样，就要做修改
            if (item.key == 'repeat') {
              _this.doTagSet(_this.selectedTask, item.key, _this.detailObj.tagsObj[item.key], false)
            } else {
              _this.doTagSet(_this.selectedTask, item.key, item.value, false)
            }
          }

        })
        //key为due need to时需要判断
        if (this.detailObj.due && !(this.selectedTask.tags && this.selectedTask.tags.due && this.detailObj.due ==
            this.selectedTask.tags.due)) {
          _this.doTagSet(_this.selectedTask, 'due', _this.detailObj.due, false)
        }
        if (this.detailObj.remind && !(this.selectedTask.tags && this.selectedTask.tags.remind && this.detailObj.remind ==
            this.selectedTask.tags.remind)) {
          _this.doTagSet(_this.selectedTask, 'remind', _this.detailObj.remind, false).then((data)=>{
                    _this.checkSetClock(_this.selectedTask);
                });
        }
        if (this.detailObj.need && !(this.selectedTask.tags && this.selectedTask.tags.need && this.detailObj.need ==
            this.selectedTask.tags.need)) {
          var value = _this.detailObj.need ;
          if(value.indexOf(":")!=-1) value = value.split(":")[0]*3600+value.split(":")[1]*60;
          _this.doTagSet(_this.selectedTask, 'need', value, false).then((data)=>{
                    _this.checkSetClock(_this.selectedTask);
                });
        }
        if (this.detailObj.leader && !(this.selectedTask.tags && this.selectedTask.tags.to && this.detailObj.leader.fuid ==
            this.selectedTask.tags.to)) {
          _this.doTagSet(_this.selectedTask, 'to', _this.detailObj.leader.fuid, false)
        }
        var btnTimer = setTimeout(function () {
          clearTimeout(btnTimer)
          _this.btnLoading = false;
          _this.tagSwiper.setWrapperTranslate(0)
          _this.tagSwiper.updateSlidesSize()
        }, 1000)

      },
      setTimeNeed: function () {
        if (!this.selectTimeNeed) {
          this.showNotice('请选择时间', 'warning')
          return;
        }
        console.log("selectTimeNeed", this.selectTimeNeed)
        this.timeNeedDialogVisible = false;
        this.detailObj.need = this.selectTimeNeed;
        this.saveTask()
      },
      chooseEvlTime: function (item) {
        this.detailObj.need = item;
        this.saveTask()
        this.clearPopoverTime()
      },
      confirmEvlTime: function () {
        var hour = this.popoverTime.hour.length === 1 ? '0' + this.popoverTime.hour : this.popoverTime.hour
        this.detailObj.need = (hour || "00") + ":" + (this.popoverTime.minute || "00")
        this.clearPopoverTime()
        this.saveTask()
      },
      clearPopoverTime: function () {
        this.popoverTime.hour = ''
        this.popoverTime.minute = ''
      },
      formatTimeNeed: function (begin, end, type) {
        var temp1 = begin.split(':');
        var temp2 = end.split(':')
        if (type == 'add') {
          var h = Number(temp1[0]) + Number(temp2[0]);
          var m = Number(temp1[1]) + Number(temp2[1]);
          var s = Number(temp1[2] || 0) + Number(temp2[2] || 0);
          if (s >= 60) {
            m = m + 1;
            s = s - 60;
          }
          if (m >= 60) {
            h = h + 1;
            m = m - 60;
          };
          h = (String(h).length < 2 ? ('0' + h) : h);
          m = (String(m).length < 2 ? ('0' + m) : m);
          s = (String(s).length < 2 ? ('0' + s) : s);
          return (h + ":" + m);
        } else if (type == 'minus') {
          var h1 = Number(temp1[0]),
            h2 = Number(temp2[0]);
          var m1 = Number(temp1[1]),
            m2 = Number(temp2[1]);
          var s1 = Number(temp1[2] || 0),
            s2 = Number(temp2[2] || 0);
          var allS = h2 * 3600 + m2 * 60 + s2 - h1 * 3600 - m1 * 60 - s1;
          var h3 = parseInt(allS / 3600);
          var m3 = parseInt((allS - h3 * 3600) / 60);
          var s3 = allS % 60;
          if (m3 < 0 || h3 < 0 || s3 < 0) {
            return '00:00:00'
          }
          h3 = (String(h3).length < 2 ? ('0' + h3) : h3);
          m3 = (String(m3).length < 2 ? ('0' + m3) : m3);
          s3 = (String(s3).length < 2 ? ('0' + s3) : s3);
          console.log(h3 + ":" + m3 + ":" + s3)
          return (h3 + ":" + m3 + ":" + s3);
        }
      },
      timeHM: function (time) {
        var str;
        if (time.length > 10) {
          str = time.substring(11);
        } else if (time.length > 5) {
          str = time.substring(5);
        } else {
          str = time
        }
        return str;
      },
      setTimeAdd: function () {
        if (!this.selectTimeAdd) {
          this.showNotice('请选择时间', 'warning')
          return;
        }
        this.timeAddDialogVisible = false;
        var timeNeed = this.selectTimeAdd;
        if (this.selectedTask.tags && this.selectedTask.tags.need) {
          timeNeed = this.formatTimeNeed(timeNeed, this.selectedTask.tags.need, 'add')
        }
        this.doTagSet(this.selectedTask, 'need', timeNeed, false)
        this.saveTask()
      },

      setTaskMember: function () {
        this.memberDialogVisible = false;
        this.detailObj.leader = this.memberListDic['fuid_' + this.selectedMember]
        this.saveTask()
      },
      showSetTagDialog: function () {
        this.notShowTagsArr = [];
        var _this = this;
        this.tagDialogVisible = true;
        console.log(this.detailObj)
        this.detailObj.tagsArr.forEach(item => {
          if (this.systemTags.indexOf(item.key) > 0 || this.tagitemDic[item.key] == undefined) {
            this.notShowTagsArr.push(item)
          }
        })
        this.commonTagsList.forEach(item => {
          item.active = false;
        })
        this.tagsRepeatList.forEach(item => {
          if (this.detailObj.tagsObj[item.key] == item.value) {
            item.active = true;
          } else {
            item.active = false;
          }
        })
        this.allTags.forEach(function (item, index, arr) {
          if (_this.detailObj.tagsObj[item.key] != undefined && _this.systemTags.indexOf(item.key) < 0) {
            item['active'] = true;
          } else {
            item['active'] = false
          }
        })
        this.projects.forEach(item => {
          if (item.id == this.selectedTask.pid) {
            item.active = true;
          } else {
            item.active = false;
          }
        })

      },
      setTaskTag: function () {
        var _this = this;
        this.detailObj.tagsObj = {};
        this.detailObj.tagsArr = [];
        this.allTags.forEach(function (item) {
          if (item['active']) {
            _this.detailObj.tagsArr.push(item);
            _this.detailObj.tagsObj[item.key] = item.name
          }
        })
        this.commonTagsList.forEach(function (item) {
          if (item['active']) {
            _this.detailObj.tagsArr.push(item);
            _this.detailObj.tagsObj[item.key] = item.name
          }
        })
        this.tagsRepeatList.forEach(function (item) {
          if (item['active']) {
            _this.detailObj.tagsArr.push(item);
            //重复和重复任务标签冲突
            _this.detailObj.tagsObj[item.key] = item.value
          }
        })
        this.projects.forEach(function (item) {
          if (item['active']) {
            _this.detailObj.tagsObj['pid'] = item.id;
          }
        })
        this.detailObj.tagsArr = this.detailObj.tagsArr.concat(this.notShowTagsArr);
        this.detailObj.tagsArr.forEach(item => {
          this.detailObj.tagsObj[item.key] = item.name
          if (item.key == 'repeat' && item.value != '') {
            this.detailObj.tagsObj[item.key] = item.value
          }
        })
        _this.tagDialogVisible = false;
        this.saveTask()
      },
      //所有标签点击
      tagsClick: function (item, type) {
        item.active = !item.active;
        if (type == 'all') {
          this.commonTagsList.forEach(item1 => {
            if (item.key == item1.key) {
              item1.active = false;
            }
          })
        } else if (type == 'common') {
          this.allTags.forEach(item1 => {
            if (item.key == item1.key) {
              item1.active = false;
            }
          })
        } else if (type == 'repeat') {
          this.tagsRepeatList.forEach(item1 => {
            if (item.value != item1.value) {
              item1.active = false
            }
          })
        } else if (type == 'project') {
          this.projects.forEach(item1 => {
            if (item.id != item1.id) {
              item1.active = false
            }
          })
        }
      },
      closeTaskDetail: function () {

        console.log(this.$route.name)
        if (this.isSwitch) {
          this.$alert('请先保存任务，然后关闭编辑器');
          return false;
        }

        if (this.$route.name == '今日任务') {
          $('.kanban-main-warp .kanban-main-container').animate({
            right: '45px'
          }, 300)
        } else {
          $('.kanban-main-warp .kanban-main-container').animate({
            right: '0px'
          }, 300)
        }
        console.log('close')
        $('.task-detail-container').animate({
          right: '-400px'
        }, 300);
      },
      getCommonTags: function () {
        api.tagsrec({}).then(data => {
          if (data.errno != 0) {
            this.showNotice(data.errmsg, 'warning');
            return Promise.reject(data.errmsg);
          }
          data.data.forEach(item => {
            item.active = false;
          })
          this.commonTagsList = data.data;
          return Promise.resolve(data);
        })
      },
      changeSwitch(e) {
        this.isSwitch = e
        this.onEditClick()
      },
      show() {
        console.log(this.$refs.dataPicker)
        this.$refs.dataPicker.pickerVisible = true
      },
      hide() {
        this.$refs.dataPicker.pickerVisible = false
      }
    },
    mounted() {
      console.log('mounted')
      this.tagSwiper = tagSlider()
      initPage();
      this.taskDetailHeight = $('.task-detail-container').height()
      var _this = this;
      this.memberList = this.members;
      this.memberList.forEach(function (item) {
        _this.memberListDic['fuid_' + item.fuid] = item;
      })
      this.allTags = this.tagitems.map(function (item, index, arr) {
        var item1 = Object.assign({}, item)
        item1['active'] = false
        return item1;
      })
      this.getCommonTags();
      this.tagsRepeatList.forEach(item => {
        this.tagsRepeatDic[item.value] = item.name;
      })

    }
  }
</script>
<style>
  #taskDetailBody {
    text-align: left;
  }

  #task-detail .title .el-input {
    width: 100%
  }

  #task-detail .title .change {
    width: 280px
  }

  .popper-task-detail.el-card__body {
    padding: 10px 0;
  }

  #task-detail button .el-loading-spinner .circular {
    width: 25px;
  }

  .popper-task-detail .el-radio-button,
  .popper-task-detail .el-radio-button__inner {
    margin: 2px;
    width: 94%;
  }

  .popper-task-detail .el-radio-button__inner {
    border-left: 1px solid #bfcbd9;
  }

  .task-detail .v-modal {
    z-index: 2000 !important;
  }

  .el-picker-panel,
  .el-select-dropdown,
  .el-popover {
    z-index: 3000 !important;
  }

  .popper-task-detail {
    font-size: .75rem;
  }

  .popper-task-detail-footer {
    margin: 0px;
    text-align: right;
    /* padding-right: 20px; */
    /* padding-top: 3px; */
    float: right;
    padding: 3px 11px 5px 0;
  }
  .datepickerchange
  {

  }
  .timepicker
  {
    width:85px !important;
    height:30px;
    position:absolute;
    top:0;
    left:0;
    cursor:pointer;
  }
  .timepicker i
  {
    display:none;
  }
  .timepicker input
  {
    border:none;
    width:85px;
    height:30px;
    opacity:0;
    cursor:pointer;
  }
  /*.el-picker-panel.el-date-picker {
    z-index: 3000 !important;
  }*/

</style>
